package cn.wolfcode.mq;

import cn.wolfcode.config.WebSocketServer;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author zhenfeng
 * @Date 2021/5/16
 *
 * 秒杀结果消费者
 */
@Component
@RocketMQMessageListener(
        consumerGroup = "MQSeckillOrderResultCustomer",
        topic = MQConstant.ORDER_RESULT_TOPIC
)
@Slf4j
public class MQSeckillOrderResultCustomer implements RocketMQListener<OrderMQResult> {
    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        log.info("进入websocket通知队列...");
        try {
            //睡眠一秒,防止发送通知时服务端和客户端还没连接
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //通过token获取指定客户端
        WebSocketServer webSocketServer = WebSocketServer.clients.get(orderMQResult.getToken());
        try {
            //推送秒杀结果
            webSocketServer.getSession().getBasicRemote().sendText(JSON.toJSONString(orderMQResult));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
